package com.caojin.propertyInjector.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

import com.caojin.propertyInjector.annotation.AnnotationResolver;

/**
 * 配置信息注入工具类
 * @author caojn
 *
 */
public class PropertyInjectorUtil {

	public static void executePropInject(Object obj,
			AnnotationResolver annotationResolver) {
		Class<?> cls = obj.getClass();
		Set<Field> fieldSet = new HashSet<Field>();
		allField(cls, fieldSet);
		try {
			for (Field f : fieldSet) {
				Annotation[] annotionArray = f.getAnnotations();
				for (Annotation annotation : annotionArray) {
					String value = annotationResolver
							.getInjectValue(annotation);
					if (value == null
							|| value == AnnotationResolver.UNRESOLVE_ANNOTATION) {
						continue;
					}
					injectField(obj, f, value);
				}
			}
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 字段注入
	 * 
	 * @param obj
	 * @param f
	 * @param property
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void injectField(Object obj, Field f, String property)
			throws IllegalArgumentException, IllegalAccessException {
		boolean accessible = f.isAccessible();
		f.setAccessible(true);
		f.set(obj, property);
		f.setAccessible(accessible);
	}

	private static void allField(Class<?> cls, Set<Field> fieldSet) {
		if (cls == null) {
			return;
		}
		for (Field f : cls.getDeclaredFields()) {
			fieldSet.add(f);
		}
		allField(cls.getSuperclass(), fieldSet);
	}
}
